It is a common pattern to validate required preconditions at the beginning of a function or block. There are two different kinds of
preconditions:
- Preconditions about argument values. An example is the assertion that a function argument lies within a specific range. An
IllegalArgumentException
should be thrown if these preconditions are violated.
- Preconditions about the state of the owner or the execution context of the function. An example is when a specific method, such as
open
, init
or prepare
, must be called before the current method can be executed. An
IllegalStateException
should be thrown if these preconditions are violated.
The Kotlin standard library provides the functions check()
, require()
, checkNotNull()
and
requireNotNull()
for this purpose. They should be used instead of directly throwing an IllegalArgumentException
or an
IllegalStateException
.
What is the potential impact?
Readability and Understanding
This change makes it easier to understand the code because the semantics of check()
, require()
,
checkNotNull()
and requireNotNull()
, as well as the fact that this is a preconditions check, are evident to the reader. When
developers share common standards and idioms, they need to spend less effort understanding each other’s code.
Code Redundancy
Using a built-in language feature or a standard API is always better than a custom implementation, because the reimplementation of something that
already exists is unnecessary.
Consistency
When check()
, require()
, checkNotNull()
and requireNotNull()
are used in an idiomatic way,
there is more consistency in what kind of exception is thrown in which situation.